package com.star.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.star.NotFoundException;
import com.star.pojo.Type;
import com.star.service.BlogService;
import com.star.service.impl.BlogServiceImpl;
import com.star.service.impl.TagServiceImpl;
import com.star.service.impl.TypeServiceImpl;
import com.star.util.MarkdownUtils;
import com.star.vo.DetailedBlog;
import com.star.vo.FirstPageBlog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private BlogServiceImpl blogService;
    @Autowired
    private TypeServiceImpl typeService;
    @Autowired
    private TagServiceImpl tagService;

    @GetMapping("/")
    public String index(Model model, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum){
        String orderBy = "create_time desc";
        PageHelper.startPage(pageNum,10,orderBy);
        List<FirstPageBlog> firstPageBlog = blogService.getFirstPageBlog();
        PageInfo<FirstPageBlog> pageInfo = new PageInfo<>(firstPageBlog);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("blogTop",blogService.getBlog(10));//阅读排行榜 id 标题 views
        model.addAttribute("types", typeService.getAllTypeAndBlog());
        model.addAttribute("tags", tagService.getAllTagAndBlog());
        System.out.println(pageInfo.toString());
        return "index";
    }

    //根据标题查询博客
    @PostMapping("/search")
    public String searchBlog(Model model, String query, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum) {
        String orderBy = "create_time desc";
        PageHelper.startPage(pageNum, 10, orderBy);
        List<FirstPageBlog> firstPageBlog = blogService.searchFirstBlogByTitle(query);//获取数据
        PageInfo<FirstPageBlog> pageInfo = new PageInfo<>(firstPageBlog);//数据分页后的详细信息
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("query", query);
        return "search";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable("id") Long id, Model model){
        DetailedBlog blog = blogService.getDetailedBlog(id);
        if (blog == null) {
            throw new NotFoundException("博客不存在");
        }
        //将博客内容从MarkDown格式转为HTML格式
        String content = blog.getContent();
        blog.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
        //更新访问和评论
        blogService.updateViews(id);
        blogService.getCommentCountById(id);
        model.addAttribute("blog", blog);
        model.addAttribute("blogTop",blogService.getBlog(10));//阅读排行榜 id 标题 views
        model.addAttribute("types", typeService.getAllTypeAndBlog());
        model.addAttribute("tags", tagService.getAllTagAndBlog());
        return "blog";
    }

}
